package cn.itcast.web.controller.email.task;

import cn.itcast.dao.cargo.ContractDao;
import cn.itcast.dao.system.UserDao;
import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.system.User;
import cn.itcast.web.controller.BaseController;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class Task extends BaseController {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    @Autowired
    private ContractDao contractDao;
    @Autowired
    private UserDao userDao;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendEmail() {
        Date newDate = new Date();
        String StrDate = sdf.format(newDate);
        //得到交货时间

        //查出所有的购销合同
        ContractExample contractExample = new ContractExample();
        List<Contract> List = contractDao.selectByExample(contractExample);
        Calendar cal = Calendar.getInstance();
        //遍历集合，得到每个时间提前三天的时间
        for (Contract contract : List) {
            //得到三天前的时间
            cal.setTime(contract.getDeliveryPeriod());
            //时间提前3天 单位：时
            cal.add(Calendar.HOUR, -72);
            //"yyyy-MM-dd HH:mm:ss"后
            String date = sdf.format(cal.getTime());
            //根据现在时间和合同中交货三天前的时间比较
            if (StrDate.equals(date)) {
                //根据购销合同的创建人，查找对应的用户
                String inputBy = contract.getInputBy();
                User user = userDao.findByInputBy(inputBy);
                if (user!=null){
                    //发送邮箱
                    rabbitTemplate.convertAndSend("email-exchange", "user.add", user);
                    System.out.println("发送邮件");
                }

            }
        }
    }
}